import { useEffect } from 'react'
import { useFilesStore } from '@/store/modules/useFilesStore'
import MDEditor from '@uiw/react-md-editor'
import { debounce } from 'radash'
import { useShallow } from 'zustand/react/shallow'

export default function Note(): React.JSX.Element {
  const { currentFile, content, folderPath, setContent } = useFilesStore(
    useShallow((state) => ({
      currentFile: state.curState.currentFile,
      content: state.noteContent,
      folderPath: state.curState.folderPath,
      setContent: state.setContent
    }))
  )

  useEffect(() => {
    // 当内容变化时写入文件
    if (!currentFile?.path) return
    const fn = debounce({ delay: 1000 }, () => {
      window.fsApi?.writeFile(currentFile.path, content || '')
    })
    // 当组件卸载或依赖变化时，取消还未触发的任务
    return () => fn.cancel()
  }, [content, currentFile?.path])

  if (!folderPath) {
    return <div className="p-6 text-text3">请在左侧选择笔记文件夹</div>
  }

  if (!currentFile?.path) {
    return <div className="p-6 text-text3">请选择一篇 md 文档进行编辑</div>
  }

  return (
    <div className="p-4 h-full w-full overflow-auto">
      <MDEditor className="!h-full" value={content} onChange={(v) => setContent(v || '')} />
    </div>
  )
}
